package com.wpf.system.controller;

import cn.hutool.core.util.ObjectUtil;
import com.wpf.system.common.response.ResultUtils;
import com.wpf.system.common.response.ResultVO;
import com.wpf.system.entity.Asset;
import com.wpf.system.service.AssetService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/asset")
public class AssetController {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AssetService assetService;

    @GetMapping("/{uid}")
    public Asset getAssetByUid(@PathVariable("uid") Long uid){
        return assetService.getAssetByUid(uid);
    }

    @PostMapping("/key")
    public ResultVO checkAssetKey(@RequestBody Asset asset){
        if(ObjectUtil.isNotNull(asset.getAssetKey())){
            Asset assetFormSQL = assetService.getById(asset.getId());
            if(ObjectUtil.isNotNull(assetFormSQL) && passwordEncoder.matches(asset.getAssetKey(),assetFormSQL.getAssetKey())){
                return null;
            }else{
                return ResultUtils.error("密码错误！支付失败");
            }
        }else{
            return ResultUtils.error("支付密码不能为空！");
        }
    }

    @PutMapping
    public ResultVO editUserAsset(@RequestBody Asset asset){
        Asset assetFromSQL = assetService.getById(asset.getId());
        //密码加密
        assetFromSQL.setAssetKey(passwordEncoder.encode(asset.getAssetKey()));
        if(assetService.updateById(assetFromSQL)){
            return ResultUtils.success("重置支付密码成功！");
        }
        return ResultUtils.error("重置支付密码失败！");
    }
}
